package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

import java.util.LinkedList;
import java.util.List;

/**
 * 骚气方法多的是.
 * 1. 使用前序中序还原树的思路.
 * 2. 使用LeetCode本身的序列化为数组的思路.
 * 3. JSON encode和decode, 不过要引入外部库.
 * 4. 层次遍历, 加入很多null.
 * 5. 括号嵌套
 * 6. 网络协议或者HFile这种的序列化, 就是固定长度格式的, 或者把长度写进数据里的.
 *
 * <p>
 * <p>
 * 错误思路
 *
 * @author tzp
 * @since 2020/10/13
 */
public class LC297 implements TreeProblem {
    List<List<Integer>> data;

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "";
        data = new LinkedList<>();
        ser(root, 0);
        StringBuilder sb = new StringBuilder();
        for (List<Integer> datum : data) {
            for (Integer integer : datum) {
                sb.append(integer).append(",");
            }
            if (sb.charAt(sb.length() - 1) == ',') {
                sb.deleteCharAt(sb.length() - 1);
            }
            sb.append("|");
        }
        if (sb.charAt(sb.length() - 1) == '|') {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public void ser(TreeNode root, int level) {
        if (data.size() < level + 1) {
            data.add(new LinkedList<>());
        }
        if (root == null)
//        data.get(level).add(root.val)
            ser(root.left, level + 1);
        ser(root.right, level + 1);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        return null;
    }

    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        String xx = new LC297().serialize(treeNode);
        System.out.println(xx);
        TreeNode oo = new LC297().deserialize(xx);
        System.out.println(oo);
    }
}
